// ~ CopyRight © 2012 USTC SINOVATE  SOFTWARE CO.LTD All Rights Reserved.

package com.guanyun.nfw.baselib.jmail;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;


/*
 * 邮箱发送辅助类
 * @author skycc
 * @date 2014-11-16
 */
public class MailUtil {

    // 发件人 账号和密码
    public static final String MY_EMAIL_ACCOUNT = "guanyunkeji@163.com";
    public static final String MY_EMAIL_PASSWORD = "guanyun123";// 密码,是你自己的设置的授权码

    // SMTP服务器(这里用的163 SMTP服务器)
    public static final String MEAIL_163_SMTP_HOST = "smtp.163.com";
    public static final String SMTP_163_PORT = "25";// 端口号,这个是163使用到的;QQ的应该是465或者875

    // 收件人
    public static final String RECEIVE_EMAIL_ACCOUNT = "guanyunkeji@163.com";

    public static void send163Mail(String Recipients, String subject, String body, Attatchment attatchment)
            throws Exception {

        Properties p = new Properties();
        p.setProperty("mail.smtp.host", MEAIL_163_SMTP_HOST);
        p.setProperty("mail.smtp.port", SMTP_163_PORT);
        p.setProperty("mail.smtp.socketFactory.port", SMTP_163_PORT);
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY");

        Session session = Session.getInstance(p, new Authenticator() {
            // 设置认证账户信息
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);
            }
        });
        session.setDebug(true);
        System.out.println("创建邮件");
        MimeMessage message = new MimeMessage(session);
        // 发件人
        message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT));
        // 收件人和抄送人
        message.setRecipients(Message.RecipientType.TO, RECEIVE_EMAIL_ACCOUNT);
        message.setSubject(subject);
//        message.setContent(body, "text/html;charset=UTF-8");
        message.setSentDate(new Date());

        //内容
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(body,  "text/html;charset=UTF-8");

        Multipart _multipart = new MimeMultipart();
        _multipart.addBodyPart(messageBodyPart);

        //附件
        if (attatchment != null) {
            _multipart.addBodyPart(addAttachment(attatchment));
        }

        message.setContent(_multipart);

        message.saveChanges();
        System.out.println("准备发送");
        Transport.send(message);

    }

    public static BodyPart addAttachment(Attatchment attatchment) throws Exception {

        BodyPart messageBodyPart = new MimeBodyPart();

        DataSource source = new ByteArrayDataSource(attatchment.getBytes(), attatchment.getType());

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName("screenshot.jpg");

       return messageBodyPart;

    }

	public static void test() {
		try {
//			sendEmail("smtp.126.com", "411944058@qq.com", "系统测试邮件",
//					"hi,all,I am AnChao!111", "anchaodaren@126.com",
//					"anchaodaren", "*******************");

//			sendEmail("smtp.163.com", "guanyunkeji@163.com", "系统测试邮件",
//					"hi,all,I am AnChao!111", "guanyunkeji@163.com",
//					"宁东党建APP", "~~guanyun123");
//            send163Mail("iihe602@163.com", "nfw：发送163邮件，上报console日志", "<b>错误日志</b>", new String[]{});
//			PropertiesUtil util = new PropertiesUtil("sysConfig.properties");
//			sendEmail(util.readProperty("mail.smtpHost"), "411944058@qq.com","系统测试邮件",
//					"hi,all,I am AnChao!nana", util.readProperty("mail.sender"),
//					util.readProperty("mail.user"), util.readProperty("mail.pwd"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static class Attatchment {

        private byte[] bytes;
        private String type;

        public Attatchment(byte[] bytes, String type) {
            this.bytes = bytes;
            this.type = type;
        }

        public static Attatchment createAttatchment(byte[] bytes, String type) {
            return new Attatchment(bytes, type);
        }

        public byte[] getBytes() {
            return this.bytes;
        }

        public String getType() {
            return this.type;
        }
    }

}
